package com.shensi.appCollect.pay.service.impl;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.shensi.appCollect.config.BasicInfo;
import com.shensi.appCollect.constantEnum.TianQuetechPayTypeEnum;
import com.shensi.appCollect.param.request.TradeReverseScanPayParameter;
import com.shensi.appCollect.pay.service.PaymentStrategy;
import com.shensi.appCollect.pojo.TradeReverseScanPayNotifyDO;
import com.shensi.appCollect.service.TradePaymentRecordsService;
import com.shensi.appCollect.utils.ApiRequestBean;
import com.shensi.appCollect.utils.HttpUtils;
import com.shensi.appCollect.utils.RSASignature;
import com.shensi.appCollect.utils.ResultData;
import com.shensi.appCollect.utils.sxfpay.SXFPayUtil;

import lombok.NoArgsConstructor;

@Service
@NoArgsConstructor
public class TianQuetechPay implements PaymentStrategy {

	private TradeReverseScanPayParameter param;
	private TianQuetechPayTypeEnum enums;
    //合作方私钥 
//	private String privateKey = "MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQCzsbkXTjrpxzSAlJK4oELORda7IfiSrZynohKVRzb8m+7PfvVw5INL6w3raAhWRM5AMo7jwUPGAJsxFHr5p8QGhCH4giJhnvvVLS3TT67dkODXVQ/tZ6pN+I3SKwKim/mvZKR/sIFdj8+hdfL3MjrEvn/qa4Fyc4tePl8xDWlxFXC0n+WffOEgAa0dhLq4PqszLvusQClJk1nSseuMPIS4BTJQgTrEDWalZ6MhopaAd+hAjhb//kG3Ym91Q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qM/8gE1WmXJUeLiFZmZg8bSQUdrMa+OMSI+4KkOEY68HlQrwl+pMbAP1v2pBtGv5/L5YAzwPqcBmaAuM9oqECgYEAwhdwTLvxx5TWC1HaQhSP7K7wPX0/DFLzmwdHfKs2711mtnBiTUzuMyvMQ5hSY2ABJ+xBMe7Ts5sujj+hp4zMur/G9okQQxKdtBxx5HgAp7DW9TQaQNmso0MfefNkhkNB5AmML8ywAnzoTMLAZa9GtqW/TKTgUUkDQ1TXo23S8JA=";
	private static Logger logger =(Logger) LoggerFactory.getLogger(TianQuetechPay.class);
	
	public TianQuetechPay(TradeReverseScanPayParameter param,TianQuetechPayTypeEnum enums) {
		this.param=param;
		this.enums=enums;
	}
	
	@Override
	public String pay() {
		logger.info("随行支付开始|商户订单号："+param.getOrdNo());
		switch (enums) {
		case ORDER_REVERSE_SCAN:
			return tradeReverseScanPay();
		case ORDER_REVERSE_EYST:
			// TODO 接入第二种支付。。。
			return null;
		default:
			return null;
		}
	}
	
	/**
	 * 天阙随心支付-被动扫码
	 * @return
	 */
	private String tradeReverseScanPay() {
		ApiRequestBean<JSONObject> reqBean = new ApiRequestBean<JSONObject>();
		logger.info("随行支付-被动扫码开始"+param.getOrdNo());
        reqBean.setSignType("RSA");
        reqBean.setVersion("1.0");
        JSONObject reqData = (JSONObject) JSONObject.toJSON(param);
        reqBean.setReqData(reqData);
        reqBean.setOrgId(param.getOrgId());
        reqBean.setReqId(param.getReqId());
        reqBean.setTimestamp(param.getTimestamp());
        //业务参数
        reqData.put("mno", param.getMno()); //商户编号
        reqData.put("notifyUrl", BasicInfo.PAY_NAMEURL+BasicInfo.TRADE_REVERSE_PAY_NOTIFYURL); //回调地址
        reqData.put("ordNo", param.getOrdNo()); //商户订单号
        reqData.put("authCode", param.getAuthCode()); //授权码
        reqData.put("amt", param.getAmt()); //订单总金额
        reqData.put("subject", param.getSubject()); //订单标题
        reqData.put("trmIp", param.getTrmIp());
        reqBean.setReqData(reqData);
        String req = JSONObject.toJSONString(reqBean);
        logger.debug("req="+req);
        //此处不要改变reqData里面值的顺序用LinkedHashMap
        @SuppressWarnings("unchecked")
		HashMap<String, Object> reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
        //组装加密串
        String signContent = RSASignature.getOrderContent(reqMap);
        logger.debug("拼接后的参数：" + signContent);
		try {
			String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, BasicInfo.TRADE_REVERSE_PAY_PRIVATEKEY));
			logger.debug("============签名:" + sign);
	        reqMap.put("sign", sign);
	        String reqStr = JSON.toJSONString(reqMap);
	        logger.debug("请求参数reqMap:" + reqMap);
	        logger.debug("请求参数reqStr:" + reqStr);
	        String resultJson = HttpUtils.connectPostUrl(BasicInfo.TRADE_REVERSE_PAY_TIANQUEURL+BasicInfo.TRADE_REVERSE_PAY_REVERSESCANURL, reqStr);
	        //不要对reqData排序 所以用LinkedHashMap
	        @SuppressWarnings("unchecked")
			HashMap<String, Object> result = JSON.parseObject(resultJson, LinkedHashMap.class, Feature.OrderedField);
	        if ("0000".equals(result.get("code"))) {
	        	logger.info("result:"+result.toString());
	            JSONObject jsobject=new JSONObject(result);
	            return jsobject.getString("respData");
	        }
            logger.info("result:"+result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 订单查询
	 * @return
	 */
	@Override
	public String tradeQueryOrder() {
		ApiRequestBean<JSONObject> reqBean = new ApiRequestBean<JSONObject>();
		logger.info("随行支付-订单查询"+param.getOrdNo());
        reqBean.setSignType("RSA");
        reqBean.setVersion("1.0");
        JSONObject reqData = (JSONObject) JSONObject.toJSON(param);
        reqBean.setReqData(reqData);
        reqBean.setOrgId(param.getOrgId());
        reqBean.setReqId(param.getReqId());
        reqBean.setTimestamp(param.getTimestamp());
        //业务参数
        reqData.put("mno", param.getMno()); //商户编号
        reqData.put("ordNo", param.getOrdNo()); //商户订单号
        reqBean.setReqData(reqData);
        String req = JSONObject.toJSONString(reqBean);
        //此处不要改变reqData里面值的顺序用LinkedHashMap
        @SuppressWarnings("unchecked")
		HashMap<String, Object> reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
        //组装加密串
        String signContent = RSASignature.getOrderContent(reqMap);
        logger.debug("拼接后的参数：" + signContent);
		try {
			String sign = RSASignature.encryptBASE64(RSASignature.sign(signContent, BasicInfo.TRADE_REVERSE_PAY_PRIVATEKEY));
			logger.debug("============签名:" + sign);
	        reqMap.put("sign", sign);
	        String reqStr = JSON.toJSONString(reqMap);
	        String resultJson = HttpUtils.connectPostUrl(BasicInfo.TRADE_REVERSE_PAY_TIANQUEURL+BasicInfo.TRADE_REVERSE_PAY_TRADEQUERYURL, reqStr);
	        //不要对reqData排序 所以用LinkedHashMap
	        @SuppressWarnings("unchecked")
			HashMap<String, Object> result = JSON.parseObject(resultJson, LinkedHashMap.class, Feature.OrderedField);
	        if ("0000".equals(result.get("code"))) {
	        	logger.info("result:"+result.toString());
	            JSONObject jsobject=new JSONObject(result);
	            return jsobject.getString("respData");
	        }
            logger.info("result:"+result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	
//	private String request
	
	

}
